'use strict';

const Controller = require('egg').Controller;
const { errors } = require('./../errors');
const _ = require('lodash');

module.exports = class BaseController extends Controller {
  success(ctx, res, code = 'ok', message = 'ok') {
    if (Array.isArray(res)) {
      res = { list: res };
    }
    ctx.body = {
      code,
      message,
      data: res,
    };
    ctx.status = 200;
    this.errors = errors;
  }

  async create() {
    const { ctx } = this;
    const payload = ctx.request.body || {};
    this.preCreate && this.preCreate(payload);
    ctx.validate(this.service.rules.create, payload);
    const res = await this.service.create(payload);
    this.postCreate && (await this.postCreate(res));
    this.success(ctx, res);
  }

  async update() {
    const { ctx } = this;
    const { id } = ctx.params;
    const payload = ctx.request.body || {};
    ctx.validate(this.service.rules.update, payload);
    const res = await this.service.update(id, payload);
    this.postUpdate && (await this.postUpdate(res));
    this.success(ctx, res);
  }

  async show() {
    const { ctx } = this;
    const { id } = ctx.params;
    this.preShow && this.preShow(id);
    const res = await this.service.show(id);
    this.postShow && this.postShow(id);
    this.success(ctx, res);
  }

  async index() {
    const { ctx } = this;
    const payload = ctx.query;
    this.preIndex && (await this.preIndex(payload));
    const res = await this.service.index(payload);
    this.postIndex && (await this.postIndex(payload, res));
    this.success(ctx, res);
  }

  async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;

    this.preDestroy && (await this.preDestroy(id));
    const res = await this.service.destroy(id);
    this.postDestroy && (await this.postDestroy(res));
    this.success(ctx, res);
  }
};
